import React, { useState } from 'react';
import type { AICorrectionIssue } from '@/types/aiCorrector';
import { IssueType, IssueSeverity } from '@/types/aiCorrector';
import { ComplianceStatus, RiskLevel, ComplianceType, ProgressStatus } from '@/types/work';
import type { ComplianceItem } from '@/types/work';
import { useAiCorrectorStore } from '@/stores/useAiCorrectorStore';
import { useComplianceStore } from '@/stores/useComplianceStore';
import InlineEditor from './InlineEditor';

interface IssueCardProps {
  issue: AICorrectionIssue;
  onEdit?: (issueId: string) => void;
  isEditing?: boolean;
  isModified?: boolean;
}

const IssueCard: React.FC<IssueCardProps> = ({ 
  issue, 
  onEdit,
  isEditing = false,
  isModified = false
}) => {
  // 使用上下文获取所需的方法
  const { updateComplianceItem, getModifiedItem } = useAiCorrectorStore();
  const [showDetails, setShowDetails] = useState(false);
  
  // 获取修改后的检查项数据（如果有）
  const modifiedItem = getModifiedItem(issue.id);
  
  // 从ComplianceStore获取当前选中的业务ID作为plan_id
  const getSelectedBusinessId = useComplianceStore(state => state.getSelectedBusinessId);
  const currentPlanId = getSelectedBusinessId() || '';
  
  // 创建一个默认的检查项对象，确保所有必要字段都存在
  const defaultItem: ComplianceItem = {
    id: issue.id,
    plan_id: currentPlanId, // 添加plan_id字段
    title: issue.title,
    description: '',
    guide: '',
    inspector: '',
    source_type: 'user',
    compliance_type: ComplianceType.RISK,
    compliance_status: ComplianceStatus.PARTIALLY_COMPLIANT,
    progress_status: ProgressStatus.IN_PROGRESS,
    attachments: [],
    updated_at: new Date().toISOString()
  };
  
  // 使用修改后的数据或默认数据
  const relatedItem = (modifiedItem as ComplianceItem) || defaultItem;
  
  if (!relatedItem) {
    return null;
  }
  
  // 处理编辑按钮点击
  const handleEditClick = () => {
    if (onEdit) {
      onEdit(issue.id);
    }
  };
  
  // 处理保存编辑
  const handleSaveEdit = (updatedData: any) => {
    const issueid = issue.id;
    const itemId = issue.itemId;
    updateComplianceItem(issueid, itemId, updatedData);
  };
  
  // 是否正在编辑当前问题
  const isEditingCurrent = isEditing;
  
  // 获取问题类型标签和颜色
  const getIssueTypeInfo = (type: IssueType) => {
    switch (type) {
      case IssueType.TYPO:
        return { label: '错别字', className: 'tag-issue-type' };
      case IssueType.SEMANTIC:
        return { label: '语义混乱', className: 'tag-issue-type' };
      case IssueType.RISK_LEVEL:
        return { label: '风险等级不合理', className: 'tag-issue-type' };
      case IssueType.COMPLIANCE_STATUS:
        return { label: '合规状态不合理', className: 'tag-issue-type' };
      default:
        return { label: type, className: 'tag-issue-type' };
    }
  };
  
  // 获取严重程度标签和颜色
  const getSeverityInfo = (severity: IssueSeverity) => {
    switch (severity) {
      case IssueSeverity.HIGH:
        return { label: '高', className: 'tag-severity-critical' };
      case IssueSeverity.MEDIUM:
        return { label: '中', className: 'tag-severity-medium' };
      case IssueSeverity.LOW:
        return { label: '低', className: 'tag-severity-low' };
      default:
        return { label: severity, className: 'tag-severity-low' };
    }
  };
  
  const typeInfo = getIssueTypeInfo(issue.type);
  const severityInfo = getSeverityInfo(issue.severity);
  
  // 切换详情显示
  const toggleDetails = () => {
    setShowDetails(!showDetails);
  };
  
  return (
    <div className={`bg-card text-card-foreground rounded-lg shadow-sm p-4 mb-4 border-l-4 ${isModified ? 'border-success' : 'border-muted'}`}>
      <div className="flex justify-between items-start mb-3">
        <div className="flex gap-2 items-center">
          <span className={typeInfo.className}>
            {typeInfo.label}
          </span>
          <span className={severityInfo.className}>
            {severityInfo.label}
          </span>
          {isModified && (
            <span className="tag-status-resolved">
              已修改
            </span>
          )}
        </div>
        
        <div className="flex gap-2">
          {!isEditingCurrent && (
            <button
              onClick={handleEditClick}
              className="text-zinc-500 hover:text-zinc-700 text-sm px-2 py-1 border border-zinc-200 rounded hover:bg-zinc-50"
              title="修改检查项"
            >
              修改
            </button>
          )}
          <button
            onClick={toggleDetails}
            className="text-muted-foreground hover:text-foreground text-sm px-2 py-1"
          >
            {showDetails ? '收起' : '详情'}
          </button>
        </div>
      </div>
      
      <h3 className="text-base font-medium text-foreground mb-1">
        {relatedItem.title}
      </h3>

      {issue.originalDescription && (
        <div className="mb-2 flex">
          <span className="text-sm font-medium text-muted-foreground mr-2 flex-shrink-0">检查描述:</span>
          <div className="text-sm text-foreground break-words" dangerouslySetInnerHTML={{ __html: issue.originalDescription }} />
        </div>
      )}
      
      <p className="text-sm font-medium bg-amber-50 text-amber-700 p-2 rounded-md border-l-2 border-amber-500 mb-2">{issue.description}</p>
      
      {showDetails && (
        <div className="mt-4 pt-4 border-t border-border">
          {issue.originalContent && (
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4 mb-3">
              <div className="bg-muted p-3 rounded">
                <div className="text-xs font-medium text-muted-foreground mb-1">原始内容</div>
                <p className="text-sm text-foreground whitespace-pre-wrap">{issue.originalContent}</p>
              </div>
              
              <div className="bg-success/10 p-3 rounded">
                <div className="text-xs font-medium text-success mb-1">改进建议</div>
                <p className="text-sm text-foreground whitespace-pre-wrap">{issue.suggestion}</p>
              </div>
            </div>
          )}
          
          {/* 显示变更后的内容（如果有变更） */}
          {isModified && modifiedItem && (
            <div className="mt-4 pt-4 border-t border-border/50">
              <div className="text-xs font-medium text-muted-foreground mb-2">变更后内容</div>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
                {/* 显示检查人员变更（针对错别字和语义问题） */}
                {(issue.type === IssueType.TYPO || issue.type === IssueType.SEMANTIC) && modifiedItem.inspector && (
                  <div className="bg-green-100 p-3 rounded">
                    <div className="text-xs font-medium text-green-600 mb-1">检查人员</div>
                    <p className="text-sm text-foreground whitespace-pre-wrap">
                      <span className="">{modifiedItem.inspector}</span>
                    </p>
                  </div>
                )}
                
                {/* 显示风险等级变更 */}
                {issue.type === IssueType.RISK_LEVEL && modifiedItem.risk_level && (
                  <div className="bg-green-100 p-3 rounded">
                    <div className="text-xs font-medium text-green-600 mb-1">风险等级</div>
                    <p className="text-sm text-foreground">
                      <span className={`tag-severity-${modifiedItem.risk_level.toLowerCase()}`}>
                        {modifiedItem.risk_level === RiskLevel.HIGH && '高'}
                        {modifiedItem.risk_level === RiskLevel.MEDIUM && '中'}
                        {modifiedItem.risk_level === RiskLevel.LOW && '低'}
                        {modifiedItem.risk_level === RiskLevel.NOT_APPLICABLE && '不适用'}
                      </span>
                    </p>
                  </div>
                )}
                
                {/* 显示合规状态变更 */}
                {issue.type === IssueType.COMPLIANCE_STATUS && modifiedItem.compliance_status && (
                  <div className="bg-green-100 p-3 rounded">
                    <div className="text-xs font-medium text-green-600 mb-1">合规状态</div>
                    <p className="text-sm text-foreground">
                      <span className="tag-status-active">
                        {modifiedItem.compliance_status === ComplianceStatus.FULLY_COMPLIANT && '完全合规'}
                        {modifiedItem.compliance_status === ComplianceStatus.PARTIALLY_COMPLIANT && '部分合规'}
                        {modifiedItem.compliance_status === ComplianceStatus.NON_COMPLIANT && '不合规'}
                        {modifiedItem.compliance_status === ComplianceStatus.NOT_APPLICABLE && '不适用'}
                      </span>
                    </p>
                  </div>
                )}
              </div>
            </div>
          )}
          
          <div className="mt-3 text-xs text-muted-foreground">
            检查项ID: {issue.itemId} | 问题ID: {issue.id}
          </div>
        </div>
      )}
      
      {/* 内联编辑表单 */}
      {isEditingCurrent && (
        <InlineEditor
          issue={issue}
          complianceItem={relatedItem}
          onSave={handleSaveEdit}
        />
      )}
    </div>
  );
};

export default IssueCard;
